'use strict';

const db = uniCloud.database();
const dbCmd = db.command;
const COLLECTION_NAME = 'ad_info'; // Assuming the collection name is 'ad_info' based on context

exports.main = async (event, context) => {
	const { id } = event;

	// 1. 参数校验
	if (!id || typeof id !== 'string') {
		return {
			code: -1,
			message: '订单ID无效',
			data: null
		}
	}

	try {
		// 4. 查询数据库
		const res = await db.collection(COLLECTION_NAME).doc(id).get();

		// 5. 处理查询结果
		if (!res.data || res.data.length === 0) {
			// 未找到订单
			return {
				code: -2,
				message: '未找到指定订单',
				data: null
			}
		}

		const orderDetail = res.data[0];

		// 提取并格式化前端所需字段
		const formattedData = {
			id: orderDetail._id, // Use _id from the database
			category: orderDetail.category,
			subCategory: orderDetail.subCategory,
			publishDate: orderDetail.publishDate,
			publishDays: orderDetail.publishDays,
			price: orderDetail.price,
			status: orderDetail.status,
			createTime: orderDetail.createTime, // Assuming createTime is stored appropriately (e.g., timestamp)
			content: orderDetail.content,
			contactName: orderDetail.name, // Map 'name' from DB to 'contactName' for frontend
			contactPhone: orderDetail.phone, // Map 'phone' from DB to 'contactPhone' for frontend
            needInvoice: orderDetail.needInvoice,
            paymentMethod: orderDetail.paymentMethod,
            remark: orderDetail.remark,
            updateTime: orderDetail.updateTime
			// Add any other fields required by the frontend here
		};

        // TODO: Implement security check if needed
        // Example: Check if the logged-in user owns this order
        // const uid = context.UID;
        // if (orderDetail.user_id !== uid && !context.auth.role.includes('admin')) { // Assuming user_id field exists
        //     return {
        //         code: -10,
        //         message: '无权查看此订单',
        //         data: null
        //     }
        // }


		// 6. 格式化成功响应
		return {
			code: 0,
			message: '获取订单详情成功',
			data: formattedData
		};

	} catch (error) {
		console.error('Error fetching order detail:', error);
		// 查询出错
		return {
			code: -50,
			message: '数据库查询失败，请稍后再试',
			data: null
		};
	}
}; 